package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.RiskDimension
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class OtherCollateralController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService

    def index(Integer max)
    {

        params.max = 10
        def offset = params.offset ? params.offset.toInteger() : 0
        
        def user = User.findById(springSecurityService.principal.id)
        String sql = "from Collateral e where e.status = 'Completed' and e.type.code = 'otherCollateral' and e.account.id in " + Account.FilterAccountSql(user)
        def city = params['city']
        if (city)
        {
            sql += " and e.city.id = ${city}"
        }
        def risk = params['risk']
        if (risk)
        {
            def riskList = RiskDimension.list()
            riskList.each {
                if (it?.label == risk)
                {
                    def minValue = it.minValue / 100
                    def maxValue = it.maxValue / 100
                    sql += " and e.cltv > ${minValue} and e.cltv <= ${maxValue} "
                }
            }
        }
        def estateStatus = params['estateStatus']
        if (estateStatus)
        {
            sql += " and e.estateStatus.id = ${estateStatus}"
        }
        def name = params['name']
        if (name && name != "")
        {
            sql += " and e.name like '%${name}%'"
        }
        def mortgageStatus = params['mortgageStatus']
        if (mortgageStatus)
        {
            sql += " and e.otherCollateral.mortgageStatus.id = ${mortgageStatus}"
        }

        def cashability = params['cashability']
        if (cashability)
        {
            sql += " and e.cashability.id = ${cashability}"
        }
        def type = params['type']
        if (type)
        {
            sql += " and e.otherCollateral.type.id = ${type}"
        }
        def rightsType = params['rightsType']
        if (rightsType)
        {
            sql += " and e.otherCollateral.rightsType.id = ${rightsType} "
        }
        String countSql = "select count(e.id) " + sql
        def count = Collateral.executeQuery(countSql)
        sql += " order by e.modifiedDate desc"

        def collateralList = Collateral.findAll(sql, [max: max, offset: offset])
        respond collateralList, model: [collateralList: collateralList, collateralCount: count]
    }

    def show(Collateral collateral)
    {
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage
        respond collateral, model: [params: params, mortgageList: mortgageList, otherCollateral: collateral?.otherCollateral]
    }

    def create()
    {
        respond new OtherCollateral(params)
    }

    def createOtherCollateral()
    {
        def typeName = params['type']
        def rightsType = params['rightsType']
        if (typeName == "仓单")
        {
            respond new OtherCollateral(params), view: 'createWarehouseReceipt'
            return
        }
        if (typeName == "提单")
        {
            respond new OtherCollateral(params), view: 'createTakeDeliveryGoods'
            return
        }
        if (typeName == "存货")
        {
            respond new OtherCollateral(params), view: 'createStockGoods'
            return
        }
        if (typeName == "其他动产质押物")
        {
            respond new OtherCollateral(params), view: 'createOtherPledge'
            return
        }
        if (typeName == "经营权")
        {
            respond new OtherCollateral(params), view: 'createManagementRight'
            return
        }
        if (typeName == "知识产权" && rightsType == "注册商标专用权")
        {
            respond new OtherCollateral(params), view: 'createBrandUsageRight'
            return
        }
        if (typeName == "知识产权" && rightsType == "专利权")
        {
            respond new OtherCollateral(params), view: 'createPatentRight'
            return
        }
        if (typeName == "知识产权" && rightsType == "著作权")
        {
            respond new OtherCollateral(params), view: 'createCopyright'
            return
        }
        if (typeName == "其他权利质押物")
        {
            respond new OtherCollateral(params), view: 'createOtherRightPledge'
            return
        }
    }

    @Transactional
    def save(OtherCollateral otherCollateral)
    {
        if (otherCollateral == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (otherCollateral.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond otherCollateral.errors, view: 'create'
            return
        }

        otherCollateral.save flush: true

        def collateral = new Collateral()
        collateral.province = otherCollateral.province
        collateral.city = otherCollateral.city
        collateral.district = otherCollateral.district
        collateral.estateStatus = otherCollateral.estateStatus
        collateral.isEstate = otherCollateral.isEstate
        collateral.unitPrice = otherCollateral.unitPrice
        collateral.totalPrice = otherCollateral.totalPrice
        collateral.valuationDate = otherCollateral.valuationDate
        collateral.ltv = otherCollateral.ltv
        collateral.cltv = otherCollateral.cltv
        collateral.account = otherCollateral.account
        collateral.externalId = otherCollateral.externalId
        collateral.name = otherCollateral.name
        collateral.fullName = otherCollateral.fullName
        collateral.identityType = otherCollateral.identityType
        collateral.idNumber = otherCollateral.idNumber
        collateral.loanCardNumber = otherCollateral.loanCardNumber
        collateral.commonOwnerFullName = otherCollateral.commonOwnerFullName
        collateral.sharePoint = otherCollateral.sharePoint
        collateral.cashability = otherCollateral.cashability
        collateral.valueVolatility = otherCollateral.valueVolatility
        collateral.seizureOfConvenience = otherCollateral.seizureOfConvenience
        collateral.relationOfMortgagor = otherCollateral.relationOfMortgagor
        collateral.legalValidity = otherCollateral.legalValidity
        collateral.firstEvaluatePrice = otherCollateral.firstEvaluatePrice
        collateral.firstEvaluateAccount = otherCollateral.firstEvaluateAccount
        collateral.latestEvaluatePrice = otherCollateral.latestEvaluatePrice
        collateral.latestEvaluateAccount = otherCollateral.latestEvaluateAccount
        collateral.latestEvaluateDate = otherCollateral.latestEvaluateDate
        collateral.nextEvaluateDate = otherCollateral.nextEvaluateDate
        collateral.actualMortgageRate = otherCollateral.actualMortgageRate
        collateral.mortgageRateUpperLimit = otherCollateral.mortgageRateUpperLimit
        collateral.description = otherCollateral.description
        collateral.registerFullName = otherCollateral.registerFullName
        collateral.registerAccount = otherCollateral.registerAccount
        collateral.registerDate = otherCollateral.registerDate
        collateral.registerUpdateDate = otherCollateral.registerUpdateDate
        collateral.otherCollateral = otherCollateral
        collateral.sourceClass = "otherCollateral"
        collateral.type = CollateralType.findByCode("otherCollateral")
        collateral.status = "Completed"
        if (collateral.validate())
        {
            collateral.save flush: true
        }
        else
        {
            println collateral.errors
        }

        def mortgageList = params["mortgageList"]
        if (mortgageList instanceof String)
        {
            mortgageList = mortgageList?.split(",")
        }
        mortgageList.each
        {
            def mortgageCollateral = new MortgageCollateral()
            mortgageCollateral.collateral = collateral
            mortgageCollateral.mortgage = Mortgage.findById(it)
            if (mortgageCollateral.validate()) 
            {
                mortgageCollateral.save flush: true
            }
            else
            {
                println mortgageCollateral.errors
            }

            // def mortgageContact = new MortgageContact()
            // mortgageContact.mortgage = Mortgage.findById(it)
            // mortgageContact.contact = Mortgage.findById(it)?.mortgageContact
            // mortgageContact.type = ContactType.findByCode("1")
            // if (mortgageContact.validate()) 
            // {
            //     mortgageContact.save flush: true    
            // }
            // else
            // {
            //     println mortgageContact.errors
            // }
        }
        
        redirect action: 'show', params: [id: collateral?.id]
    }

    def edit(OtherCollateral otherCollateral)
    {
        respond otherCollateral
    }

    @Transactional
    def update(OtherCollateral otherCollateral)
    {
        if (otherCollateral == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (otherCollateral.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond otherCollateral.errors, view: 'edit'
            return
        }

        otherCollateral.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'otherCollateral.label', default: 'OtherCollateral'), otherCollateral.id])
                redirect otherCollateral
            }
            '*' { respond otherCollateral, [status: OK] }
        }
    }

    @Transactional
    def delete(OtherCollateral otherCollateral)
    {

        if (otherCollateral == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        otherCollateral.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'otherCollateral.label', default: 'OtherCollateral'), otherCollateral.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'otherCollateral.label', default: 'OtherCollateral'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

}
